import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {ObjectUtil} from '../../../utils/object-util';
import {SelectType} from '../enums';
import {DhlCommonInputComponent} from '../dhlCommonInput';

@Component({
  selector: 'dhl-select',
  templateUrl: './dhl-select.component.html'
})
export class DhlSelectComponent extends DhlCommonInputComponent implements OnInit {


  expandKeys = [];
  nodes;
  showTree = false;
  isMultiple = false;
  selectValue;
  selectType = SelectType.DEFAULT;
  @Input() allowClear = true;
  @Input() expandAll = false;
  @Input() dicCode;

  @Input()
  set type(value) {

    switch (value) {
      case SelectType.DEFAULT:
      case SelectType.MULTIPLE:
        this.selectType = value;
        this.showTree = false;
        break;

      case SelectType.TREE:
        this.showTree = true;
        break;

      case SelectType.TREEMUL:
        this.showTree = true;
        this.isMultiple = true;

    }

    if (value == SelectType.MULTIPLE || value == SelectType.TREEMUL) {
      $('[dhl-input-element]', this.inputControl.nativeElement).attr('isArray', 'true');
    }

  }

  @Input() options;
  @Input() placeholder;
  @Input() nzErrorTip;

  @Input()
  set treeData(value) {
    if (ObjectUtil.isHaveValue(value)) {
      this.expandKeys.push(value[0].key);
      value[0].children.forEach((item) => {
        this.expandKeys.push(item.key);
      });

      this.nodes = value;
    }
  }

  @Output() onBlur = new EventEmitter();

  ngOnInit() {
    if (this.dicCode) {
      this.options = this.cacheService.getOptions(this.dicCode);
    }
  }

  onChange() {

    setTimeout(() => {
      const n = $('.ant-select-selector > nz-select-item.ant-select-selection-item', this.inputControl.nativeElement).length;

      if (!this.options) {
        return;
      }
      if (n > 0) {
        this.options.forEach(item => {
          if (item.value == this.value) {
            item.hide = true;
          } else {
            item.hide = false;
          }
        });
      } else {
        this.options.forEach(item => {
          item.hide = false;
        });
        // @ts-ignore
        this.value = '#EMPTY';
      }

      this.valueChange.emit(this.value);
    }, 50);


  }

  reset() {
    if (this.options) {
      this.options.forEach(item => {
        item.hide = false;
      });
      this.value = this.defaultValue;
    }
  }

  afterInitValue(value) {

    if (!ObjectUtil.isHaveValue(value)) {
      this.inputValue = undefined;
    }

    if (this.selectType == SelectType.DEFAULT && ObjectUtil.isArray(this.inputValue)) {
      this.inputValue = this.inputValue[0];
    }


    setTimeout(() => {
      if (this.options) {
        this.options.forEach(item => {
          if (item.value == this.value) {
            item.hide = true;
          } else {
            item.hide = false;
          }
        });
      }
    }, 100);

  }

  blur() {
    this.onBlur.emit();
  }

}


